<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hash模式测试</title>
</head>
<body>
  <!-- hash模式 -->
  <!-- <a href="#/a">a页面</a>
  <a href="#/b">b页面</a> -->
  <!-- history模式 -->
  <a onClick="goA">a页面</a>
  <a onClick="goB">b页面</a>
  <div id="app"></div>
  <script>
    // hash模式
    // let fn = () => {
    //   app.innerHTML = window.location.hash
    // }
    // fn()
    // window.addEventListener('hashchange', () => {
    //   fn()
    // })

    // history模式
    let fn = () => {
      app.innerHTML = window.location.pathname
    }
    fn()
    function goA() {
      history.pushState({}, null, '/a')
      fn()
    }

    function goB() {
      history.pushState({}, null, '/b')
      fn()
    }
    // 只对浏览器的前进和后退进行处理
    window.addEventListener('popstate', () => {
      fn()
    })
  </script>
</body>
</html>